package com.woniuxy.uums.controller;

import com.woniuxy.common.dto.WcnUserDto;
import com.woniuxy.common.utils.ResponseEnum;
import com.woniuxy.common.utils.ResponseUtil;
import com.woniuxy.uums.pojo.WcnUser;
import com.woniuxy.uums.service.WcnUserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.woniuxy.common.utils.UserUtil.getUser2;

/**
 * @author ：yolo
 * @date ：Created in 2025/6/30 11:15
 * @description：
 * @modified By：
 * @version: $
 */
@RestController
@AllArgsConstructor
public class LoginController {
    private WcnUserService uumsService;

    @PostMapping("/login")
    public ResponseUtil login(@RequestParam String username, @RequestParam String password){
        String token = uumsService.login(username, password);
        if (token != null) {
            return ResponseUtil.success(token);
        } else {
            return ResponseUtil.error("用户名或密码错误");
        }
    }

    @GetMapping("/queryUserById/{id}")
    public WcnUser queryUserById(@PathVariable("id") Long id){
        return uumsService.getById(id);
    }

    @GetMapping("/queryUser")
    public WcnUser queryUser(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 从Authorization头中获取Token
        String token = request.getHeader("Authorization");
        WcnUserDto wcnUserDto1 = getUser2(token);
        return uumsService.getById(wcnUserDto1.getId());
    }
    @PostMapping("/faceLogin")
    @ResponseBody
    public ResponseUtil faceLogin(@RequestParam String faceImage) {
        try {
            String token = uumsService.faceLogin(faceImage);
            if (token != null) {
                return ResponseUtil.get(ResponseEnum.OK,token);
            }
            return ResponseUtil.get(ResponseEnum.Fail);
        } catch (Exception e) {
            return ResponseUtil.get(ResponseEnum.Fail,e.getMessage());
        }
    }
}
